package com.wsc.services.controller;

import com.wsc.domain.MarketFile;
import com.wsc.services.util.FastDfsApiOpr;
import com.wsc.tools.AjaxResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestBody MultipartFile file){
        try {
            String name = file.getOriginalFilename();
            String type = name.substring(name.lastIndexOf(".")+1);
            String id = FastDfsApiOpr.upload(file.getBytes(),type);
            return AjaxResult.getInstance().setMsg("上传成功").setData(id);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getInstance().setCode(500).setMsg("上传失败");
        }
    }

    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody  MarketFile file){
        if(file != null){
            String[] files = file.getId().split("/");
            String group = files[1];
            String fileName = files[2]+"/"+files[3]+"/"+files[4]+"/"+files[5];
            try{
                FastDfsApiOpr.delete(group,fileName);
                return AjaxResult.getInstance().setMsg("删除成功");
            }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.getInstance().setCode(500).setMsg("删除失败");
            }
        }
        return AjaxResult.getInstance().setCode(500).setMsg("删除失败");
    }


}
